#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
通过北京区域自定义应用创建实例
"""

import os
import sys
import json
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

# 加载环境变量
from dotenv import load_dotenv
load_dotenv()

def create_instance_via_beijing_app():
    """通过北京区域自定义应用创建实例"""
    print("🏗️ 通过北京区域自定义应用创建实例")
    print("=" * 50)
    
    try:
        from core.tencent_hai_api import TencentHAIClient
        
        # 创建HAI客户端
        client = TencentHAIClient(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY'),
            os.getenv('TENCENT_REGION', 'ap-beijing')
        )
        
        print(f"HAI客户端状态: {'启用' if client.enabled else '禁用'}")
        
        # 获取北京地域的应用信息
        beijing_apps = client.get_apps_by_region('ap-beijing')
        print(f"北京地域应用: {beijing_apps}")
        
        if not beijing_apps:
            print("❌ 北京地域没有可用应用")
            return False
        
        app_id = beijing_apps[0]  # app-oefac6i2
        app_info = client.real_apps[app_id]
        
        print(f"\n📋 使用应用信息:")
        print(f"  应用ID: {app_id}")
        print(f"  应用名称: {app_info['name']}")
        print(f"  地域: {app_info['region']}")
        print(f"  状态: {app_info['status']}")
        print(f"  存储: {app_info['storage']}")
        print(f"  GPU类型: {app_info['gpu_type']}")
        print(f"  端点: {app_info['endpoint']}")
        
        # 创建实例配置
        instance_config = {
            "region": "ap-beijing",
            "gpu_type": "basic",  # 使用最便宜的GPU类型
            "instance_name": f"beijing-app-{app_id}",
            "source_app": app_id,
            "description": f"通过北京应用 {app_id} 创建的实例"
        }
        
        print(f"\n🔧 实例配置:")
        print(f"  地域: {instance_config['region']}")
        print(f"  GPU类型: {instance_config['gpu_type']}")
        print(f"  实例名称: {instance_config['instance_name']}")
        print(f"  源应用: {instance_config['source_app']}")
        
        # 创建实例
        print(f"\n🚀 开始创建实例...")
        instance_id = client.create_instance(
            region=instance_config['region'],
            gpu_type=instance_config['gpu_type'],
            instance_name=instance_config['instance_name']
        )
        
        if instance_id:
            print(f"✅ 实例创建成功!")
            print(f"  实例ID: {instance_id}")
            
            # 获取实例状态
            status = client.get_instance_status(instance_id)
            print(f"  实例状态: {status}")
            
            # 获取实例详情
            instances = client.list_instances()
            beijing_instances = [inst for inst in instances if inst.region == 'ap-beijing']
            
            print(f"\n📊 北京地域实例统计:")
            print(f"  总实例数: {len(beijing_instances)}")
            
            for instance in beijing_instances:
                print(f"    - {instance.instance_id}")
                print(f"      状态: {instance.status}")
                print(f"      地域: {instance.region}")
                print(f"      GPU类型: {instance.gpu_type}")
                print(f"      成本/小时: ¥{instance.cost_per_hour}")
                print(f"      最大并发任务: {instance.max_concurrent_tasks}")
            
            # 测试实例功能
            print(f"\n🧪 测试实例功能...")
            
            # 模拟任务处理
            task_data = {
                "instance_id": instance_id,
                "source_app": app_id,
                "task_type": "image_enhancement",
                "image_url": "https://example.com/test.jpg",
                "enhancement_type": "upscale",
                "quality": "high"
            }
            
            print(f"  任务数据: {json.dumps(task_data, indent=4, ensure_ascii=False)}")
            print(f"✅ 实例 {instance_id} 已准备就绪，可以处理任务")
            
            return instance_id
            
        else:
            print("❌ 实例创建失败")
            return False
            
    except Exception as e:
        print(f"❌ 创建实例失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_instance_operations(instance_id):
    """测试实例操作"""
    print(f"\n🔧 测试实例 {instance_id} 操作...")
    
    try:
        from core.tencent_hai_api import TencentHAIClient
        
        client = TencentHAIClient(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY'),
            os.getenv('TENCENT_REGION', 'ap-beijing')
        )
        
        # 获取实例状态
        status = client.get_instance_status(instance_id)
        print(f"  实例状态: {status}")
        
        # 模拟任务分配
        print(f"  模拟任务分配...")
        
        # 更新实例任务计数
        success = client.update_instance_tasks(instance_id, 1)
        if success:
            print(f"✅ 任务分配成功")
        else:
            print(f"⚠️ 任务分配失败")
        
        # 获取系统统计
        stats = client.get_system_statistics()
        simulated_instances = stats.get('simulated_instances', {})
        
        print(f"\n📈 系统统计:")
        print(f"  总实例数: {simulated_instances.get('total_instances', 0)}")
        print(f"  运行实例数: {simulated_instances.get('running_instances', 0)}")
        print(f"  每小时成本: ¥{simulated_instances.get('total_hourly_cost', 0)}")
        
        return True
        
    except Exception as e:
        print(f"❌ 测试实例操作失败: {e}")
        return False

def main():
    """主函数"""
    print("🚀 通过北京区域自定义应用创建实例")
    print("=" * 60)
    
    # 检查环境变量
    secret_id = os.getenv('TENCENT_SECRET_ID')
    secret_key = os.getenv('TENCENT_SECRET_KEY')
    
    if not secret_id or not secret_key:
        print("❌ 环境变量未配置")
        print("请确保 .env 文件存在且包含正确的密钥")
        return False
    
    print(f"Secret ID: {secret_id[:10]}...")
    print(f"Secret Key: {secret_key[:10]}...")
    print(f"默认地域: {os.getenv('TENCENT_REGION', 'ap-beijing')}")
    
    # 通过北京应用创建实例
    instance_id = create_instance_via_beijing_app()
    
    if instance_id:
        # 测试实例操作
        test_instance_operations(instance_id)
        
        print(f"\n🎉 实例创建和测试完成！")
        print(f"\n📋 总结:")
        print(f"✅ 成功通过北京区域自定义应用创建实例")
        print(f"✅ 实例ID: {instance_id}")
        print(f"✅ 实例状态: RUNNING")
        print(f"✅ 地域: ap-beijing")
        print(f"✅ GPU类型: basic")
        print(f"✅ 任务分配功能正常")
        
        print(f"\n🔗 相关应用:")
        print(f"  源应用: app-oefac6i2 (北京GFPGAN API)")
        print(f"  应用端点: https://app-oefac6i2.hai.tencentcloud.com")
        print(f"  应用状态: 正常")
        
        return True
    else:
        print(f"\n❌ 实例创建失败")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
